import { TOKEN_KEY } from './config.js';

// 获取token
export function getToken() {
    return localStorage.getItem(TOKEN_KEY);
}

// 设置token
export function setToken(token) {
    localStorage.setItem(TOKEN_KEY, token);
}

// 移除token
export function removeToken() {
    localStorage.removeItem(TOKEN_KEY);
}

// API请求封装
export async function apiRequest(url, method = 'GET', data = null, needAuth = true) {
    const headers = {
        'Content-Type': 'application/json'
    };

    if (needAuth) {
        const token = getToken();
        if (token) {
            headers['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
        }
    }

    const options = {
        method,
        headers
    };

    if (data && (method === 'POST' || method === 'PUT')) {
        options.body = JSON.stringify(data);
    }

    try {
        const response = await fetch(url, options);
        if (response.status === 401) {
            // 认证失败，清除token并跳转到登录页面
            removeToken();
            window.location.href = 'index.html';
            throw new Error('认证已过期，请重新登录');
        }
        return await response.json();
    } catch (error) {
        throw new Error(error.message || '请求失败');
    }
} 